<script setup lang="ts">
import { ref, reactive, onMounted, computed } from 'vue';
import { useRouter, useRoute } from 'vue-router';
import { showToast } from 'vant';
import { axiosrmedical } from '@/http/axiosRead';

interface TimeSlot {
  startTime: string;
  remainingSlots: number;
}

interface Doctor {
  doctorId: number;
  doctorName: string;
  jobTitle: string;
  briefly: string;
  photo: string;
  copayfee: number;
  campusId: number;
  campusName: string;
  campusAddr: string;
  departmentId: number;
  departmentName: string;
  departmentAddr: string;
  scheduleDate: string;
  totalSlotCount: number;
  remainingSlotCount: number;
  scheduleIds: number[];  // 新增：排班ID数组
  morningSchedule: {      // 新增：上午排班
    scheduleId: number;
    startTime: string;
    endTime: string;
    totalSlots: number;
    remainingSlots: number;
    hasSchedule: boolean;
    isExpired: boolean;   // 新增：是否过期
  };
  afternoonSchedule: {    // 新增：下午排班
    scheduleId: number;
    startTime: string;
    endTime: string;
    totalSlots: number;
    remainingSlots: number;
    hasSchedule: boolean;
    isExpired: boolean;   // 新增：是否过期
  };
}

const router = useRouter();
const route = useRoute();
const patientId = ref(route.query.patientId as string);
const departmentId = ref(route.query.departmentId as string);
const departmentName = ref(route.query.departmentName as string);

const doctors = ref<Doctor[]>([]);
const loading = ref(false);
const showTimePicker = ref(false);
const selectedDoctor = ref<Doctor | null>(null);
const selectedDate = ref(new Date());
const selectedTimeSlot = ref('');

// 生成未来7天的日期选择器数据
const dateOptions = computed(() => {
  const options = [];
  const today = new Date();
  
  for (let i = 0; i < 7; i++) {
    const date = new Date(today);
    date.setDate(today.getDate() + i);
    
    const day = date.getDate();
    const weekday = ['周日', '周一', '周二', '周三', '周四', '周五', '周六'][date.getDay()];
    const label = i === 0 ? '今日' : weekday;
    
    options.push({
      date: formatDate(date),
      day,
      label,
      active: formatDate(date) === formatDate(selectedDate.value)
    });
  }
  
  return options;
});

// 格式化日期为 YYYY-MM-DD
function formatDate(date: Date): string {
  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, '0');
  const day = String(date.getDate()).padStart(2, '0');
  return `${year}-${month}-${day}`;
}

// 获取医生排班信息
const fetchDoctorSchedule = async (date: string) => {
  loading.value = true;
  try {
    const res = await axiosrmedical.get('/DoctorSchedule/GetDoctorsByDepartment', {
      params: {
        departmentId: departmentId.value,
        date: date
      }
    });
    
    if (res.data && res.data.code === 200) {
      doctors.value = res.data.data || [];
    } else {
      showToast(res.data?.msg || '获取医生排班信息失败');
    }
  } catch (error) {
    console.error('获取医生排班信息出错:', error);
    showToast('网络错误，请稍后重试');
  } finally {
    loading.value = false;
  }
};

// 选择日期
const selectDate = (date: string) => {
  selectedDate.value = new Date(date);
  fetchDoctorSchedule(date);
};

// 选择医生和时间段
const selectDoctor = (doctor: Doctor) => {
  selectedDoctor.value = doctor;
  showTimePicker.value = true;
};

// 选择时间段
const selectTimeSlot = (period: string, scheduleInfo: any) => {
  if (!scheduleInfo.hasSchedule || scheduleInfo.remainingSlots <= 0 || scheduleInfo.isExpired) {
    showToast('该时段已无号源');
    return;
  }
  
  // 转换日期格式为 YYYY年MM月DD日
  const date = new Date(selectedDate.value);
  const formattedDate = `${date.getFullYear()}年${date.getMonth() + 1}月${date.getDate()}日`;
  const weekday = ['周日', '周一', '周二', '周三', '周四', '周五', '周六'][date.getDay()];
  
  // 时间段范围
  const timeRange = `${scheduleInfo.startTime}-${scheduleInfo.endTime}`;
  const selectedPeriod = period === 'morning' ? 'morning' : 'afternoon';
  
  // 跳转到确认预约页面
  router.push({
    path: '/appointment-confirm',
    query: {
      patientId: patientId.value,
      departmentId: departmentId.value,
      departmentName: departmentName.value,
      campusId: selectedDoctor.value?.campusId.toString(),
      campusName: selectedDoctor.value?.campusName,
      campusAddr: selectedDoctor.value?.campusAddr,
      doctorId: selectedDoctor.value?.doctorId.toString(),
      doctorName: selectedDoctor.value?.doctorName,
      doctorTitle: selectedDoctor.value?.jobTitle,
      scheduleDate: formatDate(selectedDate.value),
      scheduleId: scheduleInfo.scheduleId.toString(),  // 添加排班ID
      period: selectedPeriod,  // 添加时段标识
      timeRange: timeRange,    // 添加时间范围
      formattedDate: `${formattedDate} ${weekday} ${period === 'morning' ? '上午' : '下午'}`,
      timeSlot: scheduleInfo.startTime,
      fee: selectedDoctor.value?.copayfee.toString(),
      departmentAddr: selectedDoctor.value?.departmentAddr || '' // 添加科室地址
    }
  });
};

// 关闭时间选择器
const closeTimePicker = () => {
  showTimePicker.value = false;
};

// 返回上一页
const onBack = () => {
  router.back();
};

onMounted(() => {
  // 初始化加载今天的排班
  fetchDoctorSchedule(formatDate(selectedDate.value));
});
</script>

<template>
  <div class="schedule-page">
    <!-- 顶部导航栏 -->
    <van-nav-bar 
      :title="departmentName" 
      left-arrow 
      @click-left="onBack">
      <template #right>
        <div class="nav-icons">
          <span class="dot"></span>
          <span class="dot"></span>
          <span class="dot"></span>
          <span class="circle-btn"></span>
        </div>
      </template>
    </van-nav-bar>

    <div class="scrollable-content">
      <!-- 日期选择器 -->
      <div class="date-selector">
        <div class="date-header">
          <div v-for="(item, index) in dateOptions" :key="index" class="date-item">
            <div class="date-label">{{ item.label }}</div>
            <div 
              class="date-day" 
              :class="{ active: item.active }"
              @click="selectDate(item.date)"
            >
              {{ item.day }}
            </div>
          </div>
        </div>
      </div>

      <!-- 医生列表 -->
      <div class="doctor-title">坐诊医生</div>
      
      <van-loading v-if="loading" class="loading" size="24px" vertical>加载中...</van-loading>
      
      <div v-else-if="doctors.length === 0" class="empty-tip">
        当前日期暂无排班医生
      </div>
      
      <div v-else class="doctor-list">
        <div 
          v-for="doctor in doctors" 
          :key="doctor.doctorId"
          class="doctor-item"
        >
          <div class="doctor-info">
            <div class="doctor-avatar">
              <div v-if="doctor.photo && doctor.photo !== '/'" class="doctor-photo">
                <img :src="doctor.photo" alt="医生照片" />
              </div>
              <div v-else class="avatar-placeholder">{{ doctor.doctorName.substring(0, 1) }}</div>
            </div>
            <div class="doctor-details">
              <div class="doctor-name">{{ doctor.doctorName }} <span class="doctor-title">{{ doctor.jobTitle }}</span></div>
              <div class="doctor-brief">{{ doctor.briefly || '暂无简介' }}</div>
              <div class="doctor-hospital">{{ doctor.campusName }} - {{ doctor.campusAddr }}</div>
            </div>
          </div>
          <div class="doctor-fee">
            <span class="fee">¥{{ doctor.copayfee }}</span>
            <van-button 
              type="primary" 
              size="small" 
              :disabled="doctor.remainingSlotCount <= 0"
              @click="selectDoctor(doctor)"
            >
              {{ doctor.remainingSlotCount > 0 ? `剩余 ${doctor.remainingSlotCount}` : '约满' }}
            </van-button>
          </div>
        </div>
      </div>
    </div>
    
    <!-- 时间段选择弹窗 -->
    <van-popup 
      v-model:show="showTimePicker" 
      position="bottom" 
      round 
      closeable
      @close="closeTimePicker"
    >
      <div class="time-picker-container">
        <div class="time-picker-title">选择预约时间段</div>
        
        <!-- 上午时段 -->
        <div v-if="selectedDoctor?.morningSchedule?.hasSchedule" class="time-section">
          <div class="section-title">上午号源</div>
          <div class="time-slots">
            <div 
              class="time-slot-item"
              :class="{ 'slot-disabled': !selectedDoctor.morningSchedule.hasSchedule || selectedDoctor.morningSchedule.remainingSlots <= 0 || selectedDoctor.morningSchedule.isExpired }"
              @click="selectTimeSlot('morning', selectedDoctor.morningSchedule)"
            >
              <div class="time-range">{{ selectedDoctor.morningSchedule.startTime }}-{{ selectedDoctor.morningSchedule.endTime }}</div>
              <div class="slot-count">
                <template v-if="selectedDoctor.morningSchedule.isExpired">已无号源</template>
                <template v-else>剩余号源: {{ selectedDoctor.morningSchedule.remainingSlots }}</template>
              </div>
            </div>
          </div>
        </div>
        
        <!-- 下午时段 -->
        <div v-if="selectedDoctor?.afternoonSchedule?.hasSchedule" class="time-section">
          <div class="section-title">下午号源</div>
          <div class="time-slots">
            <div 
              class="time-slot-item"
              :class="{ 'slot-disabled': !selectedDoctor.afternoonSchedule.hasSchedule || selectedDoctor.afternoonSchedule.remainingSlots <= 0 || selectedDoctor.afternoonSchedule.isExpired }"
              @click="selectTimeSlot('afternoon', selectedDoctor.afternoonSchedule)"
            >
              <div class="time-range">{{ selectedDoctor.afternoonSchedule.startTime }}-{{ selectedDoctor.afternoonSchedule.endTime }}</div>
              <div class="slot-count">
                <template v-if="selectedDoctor.afternoonSchedule.isExpired">已无号源</template>
                <template v-else>剩余号源: {{ selectedDoctor.afternoonSchedule.remainingSlots }}</template>
              </div>
            </div>
          </div>
        </div>
      </div>
    </van-popup>
  </div>
</template>

<style scoped>
.schedule-page {
  height: 100%;
  display: flex;
  flex-direction: column;
  background: #f8f9fa;
}

.scrollable-content {
  flex: 1;
  overflow-y: auto;
  -webkit-overflow-scrolling: touch;
}

.nav-icons {
  display: flex;
  align-items: center;
  gap: 8px;
}

.dot {
  width: 6px;
  height: 6px;
  background: #d8d8d8;
  border-radius: 50%;
  display: inline-block;
}

.circle-btn {
  width: 18px;
  height: 18px;
  border: 1.5px solid #d8d8d8;
  border-radius: 50%;
  display: inline-block;
  margin-left: 6px;
}

.date-selector {
  background-color: #fff;
  padding: 12px 0;
  border-bottom: 1px solid #eee;
}

.date-header {
  display: flex;
  justify-content: space-around;
  padding: 0 12px;
}

.date-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  width: 40px;
}

.date-label {
  font-size: 12px;
  color: #999;
  margin-bottom: 4px;
}

.date-day {
  width: 36px;
  height: 36px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 16px;
  color: #333;
}

.date-day.active {
  background-color: #4080ff;
  color: #fff;
}

.doctor-title {
  font-size: 16px;
  font-weight: 500;
  padding: 16px;
  color: #333;
}

.doctor-list {
  padding: 0 16px;
}

.doctor-item {
  background-color: #fff;
  border-radius: 8px;
  padding: 16px;
  margin-bottom: 12px;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.05);
}

.doctor-info {
  display: flex;
  margin-bottom: 16px;
}

.doctor-avatar {
  margin-right: 12px;
}

.doctor-photo {
  width: 50px;
  height: 50px;
  border-radius: 50%;
  overflow: hidden;
}

.doctor-photo img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.avatar-placeholder {
  width: 50px;
  height: 50px;
  background-color: #eaf3fb;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 20px;
  color: #4080ff;
  font-weight: 500;
}

.doctor-details {
  flex: 1;
}

.doctor-name {
  font-size: 16px;
  font-weight: 500;
  color: #333;
  margin-bottom: 4px;
}

.doctor-title {
  font-size: 13px;
  color: #666;
  font-weight: normal;
  margin-left: 8px;
}

.doctor-brief {
  font-size: 13px;
  color: #999;
  line-height: 1.5;
  margin-bottom: 4px;
}

.doctor-hospital {
  font-size: 12px;
  color: #666;
}

.doctor-fee {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.fee {
  font-size: 16px;
  color: #ff4d4f;
  font-weight: 500;
}

.loading {
  display: flex;
  justify-content: center;
  padding: 30px 0;
}

.empty-tip {
  text-align: center;
  color: #999;
  padding: 30px 0;
}

.time-picker-container {
  padding: 20px 16px;
}

.time-picker-title {
  font-size: 18px;
  font-weight: 500;
  text-align: center;
  margin-bottom: 20px;
}

.time-section {
  margin-bottom: 20px;
}

.section-title {
  font-size: 16px;
  font-weight: 500;
  margin-bottom: 12px;
  color: #333;
}

.time-slots {
  display: flex;
  flex-wrap: wrap;
  gap: 12px;
}

.time-slot-item {
  width: 100%;
  padding: 15px;
  text-align: center;
  background-color: #f0f7ff;
  color: #4080ff;
  border-radius: 8px;
  font-size: 14px;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.05);
  transition: all 0.2s ease;
}

.time-slot-item:active {
  transform: scale(0.98);
}

.time-range {
  font-size: 16px;
  font-weight: 500;
  margin-bottom: 8px;
}

.slot-count {
  font-size: 14px;
  color: #ff6b6b;
}

.slot-disabled {
  background-color: #f5f5f5;
  color: #999;
}

.slot-disabled .slot-count {
  color: #999;
}
</style> 